/**
 * http请求模块
 * [Vue+axios统一接口管理](https://www.cnblogs.com/zczhangcui/p/9347447.html)
 * [axios 拦截 , 页面跳转, token 验证](http://www.cnblogs.com/dhsz/p/6410031.html)
 * [toast](https://youzan.github.io/vant/#/zh-CN/toast)
 */
import Vue from "vue";
import axios from "axios";
import Des from "./Crypt";
import { Toast } from 'vant';

Vue.use(Toast);
const dev = process.env.NODE_ENV === 'development'

axios.defaults.baseURL = `${CACIAAPI}/cacia-service/api`;
axios.defaults.headers.post['Content-Type'] = 'application/json';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

/**
 * 1.1 拦截器对请求对象做统一处理
 */
axios.interceptors.request.use(config => {
  // if (!dev) {
  //   const param = Object.assign({
  //     env: {
  //       os: "android",
  //       ip: "10.99.88.77",
  //       clientVersion: "1.0.1"
  //     }
  //   }, {
  //     data: config.data
  //   });
  //   config.data = Des.encrypt(JSON.stringify(param));
  // }
  return config;
});

/**
 * 1.2 拦截器对返回对象做统一处理
 */
axios.interceptors.response.use(response => {
  const {
    config,
    data,
    status
  } = response;
  const result = data;
  if (result.status.success) {
  		if(result.data != undefined){
		    return config.format ? config.format(result.data) : result.data;
  		}
  		return true;
  } else {
  	Toast(result.status.message);
    console.log(result.status.message);
  }
});

/**
 * 1.3 全局统一处理
 *
 * @param {any} apiConfig
 * @returns
 */
const withAxios = apiConfig => {
  const serviceMap = {};
  apiConfig.map(({
    name,
    url,
    method,
    format
  }) => {
    serviceMap[name] = async function (data = {}) {
      let key = "params";
      if (method === "post" || method === "put") {
        key = "data";
      }
      return axios({
        method,
        url,
        [key]: (data),
        format
      });
    };
  });
  return serviceMap;
};

export default withAxios;
